# -*- coding: utf-8 -*-

import wsgiref.handlers
import sys
import os
import string
import codecs
import random
import re
import cgi
import datetime
import time
import math
import pickle
import logging
import Cookie
import urllib
import urllib2

DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
LIB_PATH = os.path.join(DIR_PATH, "lib")
EXTRA_PATHS = []
for path in os.listdir(LIB_PATH):
    fullpath = os.path.join(LIB_PATH, path)
    if os.path.isdir(fullpath) and not path.startswith("."):
        EXTRA_PATHS.append(fullpath)
sys.path = sys.path + EXTRA_PATHS

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp

webapp.template.register_template_library('smart_if')
template.register_template_library('django.contrib.markup.templatetags.markup')

from math import sqrt
from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import search
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from datetime import datetime
from google.appengine.api import images
from models import *
from utilities import *
from django.utils import simplejson
from translator import *
from paging import *

from google.appengine.ext.webapp import template

# Set to true if we want to have our webapp print stack traces, etc
_DEBUG = True

class BaseRequestHandler(webapp.RequestHandler):
  """Supplies a common template generation function.

  When you call generate(), we augment the template variables supplied with
  the variables present in this function.
  """
  def generate(self, template_name, template_values={}):
    logincontrol = LoginControl()
    access = logincontrol.CheckAccess('admin')
    if access == 1:
      logged = True
    else:
      logged = False

    queryitems = Categoria.all()
    queryitems.filter(' menu = ', 'main')
    queryitems.order('singular')
    mcategorias = queryitems.fetch(500)
    
    queryitems = Categoria.all()
    queryitems.filter(' menu = ', 'secondary')
    queryitems.order('singular')
    scategorias = queryitems.fetch(500)

    values = {
      'request': self.request,
      'mcategorias': mcategorias,
      'scategorias': scategorias,
      'application_name': 'qstack',
      'logged': logged
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('templates', template_name))
    self.response.out.write(template.render(path, values, debug=_DEBUG))


class Index(BaseRequestHandler):
  def get(self):
    queryitems = Cosa.all()
    queryitems.order('-cosaId')
    cosas = queryitems.fetch(20)

    template_values = {
      'cosas': cosas,
    }
    self.generate('index.html', template_values)

class GoogleVerification(BaseRequestHandler):
  def get(self, page = 1):
    template_values = {
    }
    self.generate('googleverification.html', template_values)

class Tipos(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('tipos.html', template_values)

class Patrones(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('patrones.html', template_values)

class PatronesTag(BaseRequestHandler):
  def get(self, tag):

    template_values = {
    }
    self.generate('patrones-tag.html', template_values)

class Comprar(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('comprar.html', template_values)

class TiendasBroches(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('tiendas-broches.html', template_values)

class Videos(BaseRequestHandler):
  def get(self):
    queryitems = Video.all()
    queryitems.order('-pubDate')
    videos = queryitems.fetch(500)

    template_values = {
      'videos': videos
    }
    self.generate('videos.html', template_values)

class VideoPage(BaseRequestHandler):
  def get(self, slug):
    queryitems = Video.all()
    queryitems.filter(' slug = ', slug)
    items = queryitems.fetch(1)
    video = items[0]

    template_values = {
      'video': video,
    }
    self.generate('video.html', template_values)

class Revistas(BaseRequestHandler):
  def get(self):
    queryitems = Revista.all()
    queryitems.order('-pubDate')
    revistas = queryitems.fetch(500)

    template_values = {
      'revistas': revistas
    }
    self.generate('revistas.html', template_values)

class RevistaPage(BaseRequestHandler):
  def get(self, slug):
    queryitems = Revista.all()
    queryitems.filter(' slug = ', slug)
    revistas = queryitems.fetch(1)
    revista = revistas[0]

    template_values = {
      'revista': revista,
    }
    self.generate('revista.html', template_values)

class Libros(BaseRequestHandler):
  def get(self):
    queryitems = Libro.all()
    queryitems.order('-pubDate')
    libros = queryitems.fetch(500)

    template_values = {
      'libros': libros
    }
    self.generate('libros.html', template_values)

class LibroPage(BaseRequestHandler):
  def get(self, slug):
    queryitems = Libro.all()
    queryitems.filter(' slug = ', slug)
    libros = queryitems.fetch(1)
    libro = libros[0]

    template_values = {
      'libro': libro,
    }
    self.generate('libro.html', template_values)

class LibrosTipo(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('libros-tipo.html', template_values)

class Manualidades(BaseRequestHandler):
  def get(self):
    
    queryitems = Tag.all()
    queryitems.order('singular')
    tags = queryitems.fetch(500)

    template_values = {
      'tags': tags,
    }
    self.generate('manualidades.html', template_values)


class Blogs(BaseRequestHandler):
  def get(self):

    queryblogs = Blog.all()
    queryblogs.order('-pubDate')
    blogs = queryblogs.fetch(500)

    template_values = {
      'blogs': blogs
    }
    self.generate('blogs.html', template_values)
    
class BlogPage(BaseRequestHandler):
  def get(self, slug):

    queryblogs = Blog.all()
    queryblogs.filter(' slug = ', slug)
    blogs = queryblogs.fetch(1)
    blog = blogs[0]
    
    queryblogs = Blog.all()
    queryblogs.order('-pubDate')
    blogs = queryblogs.fetch(7)

    template_values = {
      'blog': blog,
      'blogs': blogs,
    }
    self.generate('blog.html', template_values)

class Privacidad(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('politica-privacidad.html', template_values)

class Historia(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('historia.html', template_values)

class QueEs(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('que-es.html', template_values)

class Usos(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('usos.html', template_values)
    
class Tipos(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('tipos.html', template_values)

class Herramientas(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('herramientas.html', template_values)


class Pegamento(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('pegamento.html', template_values)


class Tijeras(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('tijeras.html', template_values)

class QuienesSomos(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('quienes-somos.html', template_values)

class Enlaces(BaseRequestHandler):
  def get(self):

    template_values = {
    }
    self.generate('enlaces.html', template_values)

class Contacto(BaseRequestHandler):
  def get(self):
    template_values = {}
    self.generate('contacto.html', template_values)
  def post(self):
    if self.request.get("send") != "" and self.request.get("email") != "":
      name = self.request.get("name")
      email = self.request.get("email")
      message = self.request.get("message")

      # Send an email to shop owners
      mailtosend = mail.EmailMessage(sender="anabelen@gmail.com",subject="Mensaje fieltro.org de " + name + " - " + email)
      mailtosend.to = "anabelen@gmail.com"
      mailtosend.reply_to = email
      mailtosend.body = message
      try:
        mailtosend.send()
      except:
        p=0

      template_values = {
        'sent': True,
      }
      self.generate('contacto.html', template_values)
    else:
      template_values = {}
      self.generate('contacto.html', template_values)

class Tutoriales(BaseRequestHandler):
  def get(self):
    queryitems = Tutorial.all()
    queryitems.order('-pubDate')
    tutoriales = queryitems.fetch(500)

    template_values = {
      'tutoriales': tutoriales
    }
    self.generate('tutoriales.html', template_values)

class TutorialPage(BaseRequestHandler):
  def get(self, slug):

    queryitems = Tutorial.all()
    queryitems.filter(' slug = ', slug)
    items = queryitems.fetch(1)
    tutorial = items[0]

    template_values = {
      'tutorial': tutorial
    }
    
    self.generate('tutorial.html', template_values)

class SiteMap(BaseRequestHandler):
  def get(self):

    queryitems = Blog.all()
    blogs = queryitems.fetch(500)

    queryitems = Revista.all()
    revistas = queryitems.fetch(500)
    
    queryitems = Video.all()
    videos = queryitems.fetch(500)
    
    queryitems = Libro.all()
    libros = queryitems.fetch(500)
    
    queryitems = Tutorial.all()
    tutoriales = queryitems.fetch(500)

    template_values = {
      'blogs': blogs,
      'revistas': revistas,
      'videos': videos,
      'libros': libros,
      'tutoriales': tutoriales,
    }
    print "Content-Type: text/xml"
    self.generate('sitemap.xml', template_values)

class Cosas(BaseRequestHandler):
  def get(self):

    queryitems = Cosa.all()
    queryitems.order('-cosaId')
    cosas = queryitems.fetch(500)

    template_values = {
      'cosas': cosas,
    }
    self.generate('cosas.html', template_values)

class CosaPage(BaseRequestHandler):
  def get(self, slug):

    queryposts = Cosa.all()
    queryposts.filter(' slug = ', slug)
    cosas = queryposts.fetch(1)
    cosa = cosas[0]
    
    tag = cosa.tag
    categoria = cosa.categoria
    
    queryposts = Cosa.all()
    queryposts.filter(' tag = ', tag)
    tagCosas = queryposts.fetch(8)

    queryitems = Cosa.all()
    queryitems.filter(' categoria = ', categoria)
    categoriaCosas = queryitems.fetch(8)

    template_values = {
      'cosa': cosa,
      'tagCosas': tagCosas,
      'categoriaCosas': categoriaCosas,
    }
    self.generate('cosa.html', template_values)

class Favelet(BaseRequestHandler):

  def get(self):
    queryitems = Categoria.all()
    queryitems.order('plural')
    categorias = queryitems.fetch(500)

    queryitems = Tag.all()
    queryitems.order('plural')
    tags = queryitems.fetch(500)

    template_values = {
      'categorias': categorias,
      'tags': tags,
    }
    self.generate('dfavelet.js', template_values)


class CategoriaTag(BaseRequestHandler):
  def get(self, slug):
    
    queryitems = Categoria.all()
    queryitems.filter(' pluralSlug = ', slug)
    items = queryitems.fetch(1)
    
    if len(items) > 0:
      categoria = items[0]
      
      queryitems = Cosa.all()
      queryitems.filter(' categoriaSlug = ', slug)
      queryitems.order('-cosaId')
      cosas = queryitems.fetch(500)

      template_values = {
        'categoria': categoria,
        'cosas': cosas,
      }
      self.generate('categoria.html', template_values)
    else:
      queryitems = Tag.all()
      queryitems.filter(' pluralSlug = ', slug)
      items = queryitems.fetch(1)
      tag = items[0]
      
      queryitems = Cosa.all()
      queryitems.filter(' tagSlug = ', slug)
      queryitems.order('-cosaId')
      cosas = queryitems.fetch(500)

      template_values = {
        'tag': tag,
        'cosas': cosas,
      }
      self.generate('tag.html', template_values)


class PatronesCategoriaTag(BaseRequestHandler):
  def get(self, slug):
    
    queryitems = Categoria.all()
    queryitems.filter(' pluralSlug = ', slug)
    items = queryitems.fetch(1)
    
    if len(items) > 0:
      categoriatag = items[0]
      
      queryitems = Cosa.all()
      queryitems.filter(' categoriaSlug = ', slug)
      queryitems.order('-cosaId')
      cosas = queryitems.fetch(500)

      template_values = {
        'categoriatag': categoriatag,
        'cosas': cosas,
      }
      self.generate('patrones-tag.html', template_values)
    else:
      queryitems = Tag.all()
      queryitems.filter(' pluralSlug = ', slug)
      items = queryitems.fetch(1)
      categoriatag = items[0]
      
      queryitems = Cosa.all()
      queryitems.filter(' tagSlug = ', slug)
      queryitems.order('-cosaId')
      cosas = queryitems.fetch(500)

      template_values = {
        'categoriatag': categoriatag,
        'cosas': cosas,
      }
      self.generate('patrones-tag.html', template_values)

class CosaImg(BaseRequestHandler):
  def get(self, slug):

    queryposts = Cosa.all()
    queryposts.filter(' slug = ', slug)
    cosas = queryposts.fetch(1)

    if len(cosas) > 0:
      cosa = cosas[0]
      self.response.headers['Content-Type'] = "image/jpeg"
      self.response.headers['Cache-Control'] = "public, max-age=363600"
      self.response.out.write(cosa.bytes_content)
    else:
      self.error(500)
      errorlauncher = ErrorLauncher()
      errorlauncher.Launch(self,404)
      return 1


class CosaImgResized(webapp.RequestHandler):
  def get(self, slug, width, height, action):
    queryposts = Cosa.all()
    queryposts.filter(' slug = ', slug)
    cosas = queryposts.fetch(1)

    if len(cosas) > 0:
      myfile = cosas[0]
      if action=='resized':
        if height=='auto':
          content = myfile.bytes_content
          img=images.Image(content)
          originalwidth = float(img.width)
          originalheight = float(img.height)
          resizedwidth = float(width)
          resizedheight = float(float(originalheight*resizedwidth)/originalwidth)
          resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))
        elif width=='auto':
          content = myfile.bytes_content
          img=images.Image(content)
          originalwidth = float(img.width)
          originalheight = float(img.height)
          resizedheight = float(height)
          resizedwidth = float(float(originalwidth*resizedheight)/originalheight)
          resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))
        else:
          content = myfile.bytes_content
          img=images.Image(content)
          resizedwidth=float(width)
          resizedheight=float(height)
          resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))

        image = images.Image(resizedcontent)
        image.crop(0.0, 0.0, 1.0, 1.0)
        image_data = image.execute_transforms(output_encoding=images.JPEG, quality=100)

        self.response.headers['Content-Type'] = "image/jpeg"
        self.response.headers['Cache-Control'] = "public, max-age=363600"
        self.response.out.write(image_data)
      elif action=='cropped':
        width=float(width)
        height=float(height)
        content = myfile.bytes_content
        img=images.Image(content)
        originalwidth = float(img.width)
        originalheight = float(img.height)
        resizedwidth = width
        if originalwidth>=originalheight:
          resizedheight = height
          resizedwidth = (originalwidth*resizedheight)/originalheight
        if resizedwidth<=width:
          resizedwidth = width
          resizedheight = (originalheight*resizedwidth)/originalwidth

        resizedcontent = images.resize(content, int(resizedwidth), int(resizedheight))
        resizedimg=images.Image(resizedcontent)
        originalwidth = resizedimg.width
        originalheight = resizedimg.height
        relativewidth = (width/originalwidth)
        relativeheight = (height/originalheight)
        borderwidth = math.fabs((1 - relativewidth)/2)
        borderheight = math.fabs((1 - relativeheight)/2)
        left_x = borderwidth
        right_x = 1 - borderwidth
        top_y = borderheight
        bottom_y = 1 - borderheight
        #croppedcontent=images.crop(resizedcontent, left_x, top_y, right_x, bottom_y)

        image = images.Image(resizedcontent)
        image.crop(left_x, top_y, right_x, bottom_y)
        image_data = image.execute_transforms(output_encoding=images.JPEG, quality=100)

        self.response.headers['Content-Type'] = "image/jpeg"
        self.response.headers['Cache-Control'] = "public, max-age=363600"
        self.response.out.write(image_data)
      else:
        image = images.Image(file.bytes_content)
        image.crop(0.0, 0.0, 1.0, 1.0)
        image_data = image.execute_transforms(output_encoding=images.JPEG, quality=100)

        self.response.headers['Content-Type'] = "image/jpeg"
        self.response.headers['Cache-Control'] = "public, max-age=363600"
        self.response.out.write(image_data)
    else:
      self.error(500)
      errorlauncher = ErrorLauncher()
      errorlauncher.Launch(self,500)
      return 1



class SaveFavelet(BaseRequestHandler):
  def get(self):
    url = urllib.unquote(self.request.get("u"))
    title = urllib.unquote(self.request.get("t"))
    image = urllib.unquote(self.request.get("i"))
    slug = urllib.unquote(self.request.get("s"))
    category = urllib.unquote(self.request.get("c"))
    categorySlug = urllib.unquote(self.request.get("cs"))
    tag = urllib.unquote(self.request.get("ta"))
    tagSlug = urllib.unquote(self.request.get("tas"))
    description = urllib.unquote(self.request.get("d"))

    result = urlfetch.fetch(image)
    content = result.content
    
    img = images.Image(content)

    unacosa = Cosa()
    unacosa.bytes_content = db.Blob(content)
    unacosa.width = img.width
    unacosa.height = img.height
    unacosa.title = title
    unacosa.url = url
    unacosa.urlimg = image
    unacosa.slug = slug
    unacosa.tag = tag
    unacosa.tagSlug = tagSlug
    unacosa.categoria = category
    unacosa.categoriaSlug = categorySlug
    unacosa.description = description

    queryitem = Cosa.all()
    queryitem.order('-cosaId')
    items = queryitem.fetch(1)

    if not len(items) > 0:
      lastId = 0
    else:
      lastId = items[0].cosaId

    cosaId = lastId + 1
    unacosa.cosaId = cosaId

    unacosa.put()

    self.response.out.write("Saved!");

def main():
  urlmap = [
            ('/', Index),
            ('/page/(.*)/', Index),
            ('/google03e298e060fd8943.html', GoogleVerification),
            ('/blogs', Blogs),
            ('/blog/(.*)', BlogPage),
            ('/libros', Libros),
            ('/libros/(.*)', LibrosTipo),
            ('/libro/(.*)', LibroPage),
            ('/revistas', Revistas),
            ('/revista/(.*)', RevistaPage),
            ('/manualidades', Manualidades),
            ('/comprar', Comprar),
            ('/videos', Videos),
            ('/video/(.*)', VideoPage),
            ('/patrones', Patrones),
            ('/patrones/(.*)', PatronesCategoriaTag),
            ('/cosa', CosaPage),
            ('/politica-privacidad', Privacidad),
            ('/historia', Historia),
            ('/tipos', Tipos),
            ('/usos', Usos),
            ('/que-es', QueEs),
            ('/quienes-somos', QuienesSomos),
            ('/contacto', Contacto),
            ('/enlaces', Enlaces),
            ('/tutoriales', Tutoriales),
            ('/tutorial/(.*)', TutorialPage),
            ('/save/from_favelet', SaveFavelet),
            ('/herramientas', Herramientas),
            ('/pegamento', Pegamento),
            ('/tijeras', Tijeras),
            ('/cosas', Cosas),
            ('/cosa/(.*)/img', CosaImg),
            ('/cosa/(.*)/img/(.*)/(.*)/(resized)/', CosaImgResized),
            ('/cosa/(.*)/img/(.*)/(.*)/(cropped)/', CosaImgResized),
            ('/cosa/(.*)', CosaPage),
            ('/sitemap.xml', SiteMap),
            ('/favelet', Favelet),
            ('/(.*)', CategoriaTag),
           ]

  application = webapp.WSGIApplication(urlmap, debug=_DEBUG)
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

